/*
 * Copyright (c) 2025 STMROS Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "stmconn/stmconn_interface.hpp"
#include "stmconn/stmconn_serial.hpp"
#include "stmconn/stmconn_mock.hpp"
#include <regex>

namespace stmconn {

// 工厂方法实现
StmConnInterface::SharedPtr StmConnInterface::open_url(const std::string & url) {
  // 简单的URL解析
  // 支持格式: serial:///dev/ttyUSB0:115200 或直接 /dev/ttyUSB0:115200
  
  // 检查mock连接
  if (url == "mock://" || url == "mock") {
    auto conn = std::make_shared<StmConnMock>();
    if (conn->open()) {
      return conn;
    }
  }
  
  // 检查串口连接
  std::regex serial_regex("^(serial://)?(\\/dev\\/\\w+)(?::(\\d+))?");
  std::smatch match;
  
  if (std::regex_search(url, match, serial_regex)) {
    std::string device = match[2].str();
    uint32_t baudrate = 115200; // 默认波特率
    
    if (match[3].matched) {
      baudrate = std::stoi(match[3].str());
    }
    
    auto conn = std::make_shared<StmConnSerial>(device, baudrate);
    if (conn->open()) {
      return conn;
    }
  }
  
  return nullptr;
}

} // namespace stmconn